<!--
 * @Description: 系统设置页面 - 提供基本设置、业务设置、通知设置、信用评估与提醒配置、数据备份功能
 * @Author: lujq
 * @Date: 2025-08-25
 * @LastEditors: lujq
 * @LastEditTime: 2025-08-25 15:25:00
-->
<template>
  <div class="settings">
    <el-card class="settings-card">
      <template #header>
        <div class="card-header">
          <span class="card-title">系统设置</span>
        </div>
      </template>

      <el-tabs v-model="activeTab" class="settings-tabs">
        <!-- 基本设置 -->
        <el-tab-pane label="基本设置" name="basic">
          <el-form :model="basicForm" label-width="120px" class="settings-form">
            <el-form-item label="系统名称">
              <el-input v-model="basicForm.systemName" placeholder="请输入系统名称" />
            </el-form-item>
            <el-form-item label="公司名称">
              <el-input v-model="basicForm.companyName" placeholder="请输入公司名称" />
            </el-form-item>
            <el-form-item label="联系电话">
              <el-input v-model="basicForm.phone" placeholder="请输入联系电话" />
            </el-form-item>
            <el-form-item label="邮箱地址">
              <el-input v-model="basicForm.email" placeholder="请输入邮箱地址" />
            </el-form-item>
            <el-form-item label="公司地址">
              <el-input v-model="basicForm.address" type="textarea" :rows="3" placeholder="请输入公司地址" />
            </el-form-item>
            <el-form-item label="系统Logo">
              <el-upload class="logo-uploader" action="#" :show-file-list="false" :before-upload="beforeLogoUpload">
                <img v-if="basicForm.logo" :src="basicForm.logo" class="logo" />
                <el-icon v-else class="logo-uploader-icon"><Plus /></el-icon>
              </el-upload>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="saveBasicSettings">保存设置</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <!-- 业务设置 -->
        <el-tab-pane label="业务设置" name="business">
          <el-form :model="businessForm" label-width="120px" class="settings-form">
            <el-form-item label="默认客户等级">
              <el-select v-model="businessForm.defaultCustomerLevel" placeholder="请选择默认客户等级">
                <el-option label="钻石" value="diamond" />
                <el-option label="黄金" value="gold" />
                <el-option label="白银" value="silver" />
                <el-option label="青铜" value="bronze" />
              </el-select>
            </el-form-item>
            <el-form-item label="订单有效期">
              <el-input-number v-model="businessForm.orderValidDays" :min="1" :max="365" controls-position="right" />
              <span class="form-text">天</span>
            </el-form-item>
            <el-form-item label="自动确认订单">
              <el-switch v-model="businessForm.autoConfirmOrder" />
            </el-form-item>
            <el-form-item label="库存预警阈值">
              <el-input-number v-model="businessForm.stockWarningThreshold" :min="0" controls-position="right" />
            </el-form-item>
            <el-form-item label="价格精度">
              <el-select v-model="businessForm.pricePrecision" placeholder="请选择价格精度">
                <el-option label="整数" :value="0" />
                <el-option label="1位小数" :value="1" />
                <el-option label="2位小数" :value="2" />
                <el-option label="3位小数" :value="3" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="saveBusinessSettings">保存设置</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <!-- 信用评估设置 -->
        <el-tab-pane label="信用评估" name="credit">
          <el-form :model="creditForm" label-width="180px" class="settings-form">
            <el-form-item label="信用评分权重">
              <el-input-number v-model="creditForm.creditScoreWeight" :min="0" :max="100" controls-position="right" />
              <span class="form-text">%</span>
            </el-form-item>
            <el-form-item label="历史订单量/金额权重">
              <el-input-number v-model="creditForm.orderHistoryWeight" :min="0" :max="100" controls-position="right" />
              <span class="form-text">%</span>
            </el-form-item>
            <el-form-item label="回款及时性权重">
              <el-input-number v-model="creditForm.paymentPunctualityWeight" :min="0" :max="100" controls-position="right" />
              <span class="form-text">%</span>
            </el-form-item>
            <el-form-item label="合作年限/黏性权重">
              <el-input-number v-model="creditForm.relationshipWeight" :min="0" :max="100" controls-position="right" />
              <span class="form-text">%</span>
            </el-form-item>
            <el-form-item label="投诉/售后情况权重">
              <el-input-number v-model="creditForm.complaintWeight" :min="0" :max="100" controls-position="right" />
              <span class="form-text">%</span>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="saveCreditSettings">保存设置</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <!-- 提醒设置 -->
        <el-tab-pane label="提醒设置" name="remind">
          <el-form :model="remindForm" label-width="180px" class="settings-form">
            <el-form-item label="合同到期提前提醒">
              <el-input-number v-model="remindForm.contractExpireAdvanceDays" :min="0" :max="365" controls-position="right" />
              <span class="form-text">天</span>
            </el-form-item>
            <el-form-item label="应收款到期提前提醒">
              <el-input-number v-model="remindForm.receivableDueAdvanceDays" :min="0" :max="365" controls-position="right" />
              <span class="form-text">天</span>
            </el-form-item>
            <el-form-item label="客户回访提前提醒">
              <el-input-number v-model="remindForm.customerFollowupAdvanceDays" :min="0" :max="365" controls-position="right" />
              <span class="form-text">天</span>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="saveRemindSettings">保存设置</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <!-- 通知设置 -->
        <el-tab-pane label="通知设置" name="notification">
          <el-form :model="notificationForm" label-width="120px" class="settings-form">
            <el-form-item label="邮件通知">
              <el-switch v-model="notificationForm.emailEnabled" />
            </el-form-item>
            <el-form-item v-if="notificationForm.emailEnabled" label="SMTP服务器">
              <el-input v-model="notificationForm.smtpHost" placeholder="请输入SMTP服务器地址" />
            </el-form-item>
            <el-form-item v-if="notificationForm.emailEnabled" label="SMTP端口">
              <el-input-number v-model="notificationForm.smtpPort" :min="1" :max="65535" controls-position="right" />
            </el-form-item>
            <el-form-item v-if="notificationForm.emailEnabled" label="发件邮箱">
              <el-input v-model="notificationForm.senderEmail" placeholder="请输入发件邮箱" />
            </el-form-item>
            <el-form-item v-if="notificationForm.emailEnabled" label="邮箱密码">
              <el-input v-model="notificationForm.senderPassword" type="password" placeholder="请输入邮箱密码" show-password />
            </el-form-item>
            <el-form-item label="短信通知">
              <el-switch v-model="notificationForm.smsEnabled" />
            </el-form-item>
            <el-form-item label="新订单通知">
              <el-switch v-model="notificationForm.newOrderNotify" />
            </el-form-item>
            <el-form-item label="库存预警通知">
              <el-switch v-model="notificationForm.stockWarningNotify" />
            </el-form-item>
            <el-form-item label="客户流失预警">
              <el-switch v-model="notificationForm.customerChurnNotify" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="saveNotificationSettings">保存设置</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <!-- 数据备份 -->
        <el-tab-pane label="数据备份" name="backup">
          <div class="backup-section">
            <el-card class="backup-card">
              <template #header>
                <span>数据备份</span>
              </template>
              <div class="backup-content">
                <p class="backup-description">定期备份系统数据，确保数据安全。建议每天进行一次备份。</p>
                <div class="backup-actions">
                  <el-button type="primary" :loading="backupLoading" @click="createBackup">立即备份</el-button>
                  <el-button @click="downloadBackup">下载备份</el-button>
                </div>
              </div>
            </el-card>

            <el-card class="backup-card">
              <template #header>
                <span>自动备份设置</span>
              </template>
              <el-form :model="backupForm" label-width="120px">
                <el-form-item label="启用自动备份">
                  <el-switch v-model="backupForm.autoBackupEnabled" />
                </el-form-item>
                <el-form-item v-if="backupForm.autoBackupEnabled" label="备份频率">
                  <el-select v-model="backupForm.backupFrequency" placeholder="请选择备份频率">
                    <el-option label="每天" value="daily" />
                    <el-option label="每周" value="weekly" />
                    <el-option label="每月" value="monthly" />
                  </el-select>
                </el-form-item>
                <el-form-item v-if="backupForm.autoBackupEnabled" label="备份时间">
                  <el-time-picker v-model="backupForm.backupTime" format="HH:mm" value-format="HH:mm" placeholder="请选择备份时间" />
                </el-form-item>
                <el-form-item v-if="backupForm.autoBackupEnabled" label="保留天数">
                  <el-input-number v-model="backupForm.retentionDays" :min="1" :max="365" controls-position="right" />
                  <span class="form-text">天</span>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="saveBackupSettings">保存设置</el-button>
                </el-form-item>
              </el-form>
            </el-card>

            <el-card class="backup-card">
              <template #header>
                <span>备份历史</span>
              </template>
              <el-table :data="backupHistory" stripe>
                <el-table-column prop="filename" label="文件名" />
                <el-table-column prop="size" label="文件大小" width="120" />
                <el-table-column prop="createTime" label="创建时间" width="180">
                  <template #default="{ row }">
                    {{ formatDateTime(row.createTime) }}
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="150">
                  <template #default="{ row }">
                    <el-button type="primary" size="small" @click="downloadBackupFile(row)">下载</el-button>
                    <el-button type="danger" size="small" @click="deleteBackupFile(row)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-card>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { formatDateTime } from '@/utils'
import { getSystemSettings, updateSystemSettings } from '@/api/settings'

// 当前激活的标签页
const activeTab = ref('basic')

// 基本设置表单模型
const basicForm = reactive({
  systemName: '布匹销售系统',
  companyName: '某某纺织有限公司',
  phone: '400-123-4567',
  email: 'contact@company.com',
  address: '上海市浦东新区张江高科技园区',
  logo: '',
})

// 业务设置表单模型
const businessForm = reactive({
  defaultCustomerLevel: 'bronze',
  orderValidDays: 30,
  autoConfirmOrder: false,
  stockWarningThreshold: 100,
  pricePrecision: 2,
})

// 通知设置表单模型
const notificationForm = reactive({
  emailEnabled: false,
  smtpHost: '',
  smtpPort: 587,
  senderEmail: '',
  senderPassword: '',
  smsEnabled: false,
  newOrderNotify: true,
  stockWarningNotify: true,
  customerChurnNotify: true,
})

// 备份设置表单模型
const backupForm = reactive({
  autoBackupEnabled: false,
  backupFrequency: 'daily',
  backupTime: '02:00',
  retentionDays: 30,
})

// 备份历史数据
const backupLoading = ref(false)
const backupHistory = ref([
  { id: '1', filename: 'backup_20241220_020000.sql', size: '2.5MB', createTime: '2024-12-20T02:00:00.000Z' },
  { id: '2', filename: 'backup_20241219_020000.sql', size: '2.3MB', createTime: '2024-12-19T02:00:00.000Z' },
  { id: '3', filename: 'backup_20241218_020000.sql', size: '2.1MB', createTime: '2024-12-18T02:00:00.000Z' },
])

// 信用评估表单模型
const creditForm = reactive({
  creditScoreWeight: 30,
  orderHistoryWeight: 25,
  paymentPunctualityWeight: 25,
  relationshipWeight: 15,
  complaintWeight: 5,
})

// 提醒设置表单模型
const remindForm = reactive({
  contractExpireAdvanceDays: 7,
  receivableDueAdvanceDays: 5,
  customerFollowupAdvanceDays: 30,
})

/**
 * Logo上传前校验与预览
 * @param file 待上传文件
 * @returns 是否通过校验
 */
const beforeLogoUpload = (file: File) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isJPG) {
    ElMessage.error('Logo只能是 JPG/PNG 格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('Logo大小不能超过 2MB!')
    return false
  }
  const reader = new FileReader()
  reader.onload = (e) => {
    basicForm.logo = e.target?.result as string
  }
  reader.readAsDataURL(file)
  return false
}

/** 保存基本设置 */
const saveBasicSettings = () => {
  ElMessage.success('基本设置保存成功')
}

/** 保存业务设置 */
const saveBusinessSettings = () => {
  ElMessage.success('业务设置保存成功')
}

/** 保存通知设置 */
const saveNotificationSettings = () => {
  ElMessage.success('通知设置保存成功')
}

/** 保存备份设置 */
const saveBackupSettings = () => {
  ElMessage.success('备份设置保存成功')
}

/** 创建数据备份（模拟） */
const createBackup = async () => {
  backupLoading.value = true
  try {
    await new Promise((resolve) => setTimeout(resolve, 1500))
    const now = new Date()
    const filename = `backup_${now.getFullYear()}${(now.getMonth() + 1).toString().padStart(2, '0')}${now.getDate().toString().padStart(2, '0')}_${now.getHours().toString().padStart(2, '0')}${now.getMinutes().toString().padStart(2, '0')}${now.getSeconds().toString().padStart(2, '0')}.sql`
    backupHistory.value.unshift({ id: Date.now().toString(), filename, size: '2.8MB', createTime: now.toISOString() })
    ElMessage.success('数据备份创建成功')
  } catch (e) {
    ElMessage.error('数据备份创建失败')
  } finally {
    backupLoading.value = false
  }
}

/** 下载最新备份（模拟） */
const downloadBackup = () => {
  ElMessage.info('备份下载功能开发中...')
}

/** 下载指定备份（模拟） */
const downloadBackupFile = (row: { filename: string }) => {
  ElMessage.info(`下载备份文件: ${row.filename}`)
}

/** 删除指定备份（模拟） */
const deleteBackupFile = async (row: { id: string; filename: string }) => {
  try {
    await ElMessageBox.confirm(`确定要删除备份文件 "${row.filename}" 吗？`, '删除确认', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' })
    const index = backupHistory.value.findIndex((item) => item.id === row.id)
    if (index > -1) {
      backupHistory.value.splice(index, 1)
      ElMessage.success('备份文件删除成功')
    }
  } catch (error) {
    if (error !== 'cancel') ElMessage.error('备份文件删除失败')
  }
}

/**
 * 拉取系统设置（信用评估与提醒配置）
 */
const fetchSystemSettings = async () => {
  try {
    const { data } = await getSystemSettings()
    if (data) {
      if (data.creditAssessment) Object.assign(creditForm, data.creditAssessment)
      if (data.remind) Object.assign(remindForm, data.remind)
    }
  } catch (e) {
    // 忽略错误，使用默认值
  }
}

/** 保存信用评估设置 */
const saveCreditSettings = async () => {
  await updateSystemSettings({ creditAssessment: { ...creditForm } })
  ElMessage.success('信用评估设置已保存')
}

/** 保存提醒设置 */
const saveRemindSettings = async () => {
  await updateSystemSettings({ remind: { ...remindForm } })
  ElMessage.success('提醒设置已保存')
}

onMounted(() => {
  fetchSystemSettings()
})
</script>

<style scoped>
.settings { padding: 0; }
.settings-card { min-height: 600px; }
.card-header { display: flex; justify-content: space-between; align-items: center; }
.card-title { font-size: 18px; font-weight: 600; color: #303133; }
.settings-tabs { margin-top: 20px; }
.settings-form { max-width: 600px; margin-top: 20px; }
.form-text { margin-left: 8px; color: #909399; font-size: 14px; }
.logo-uploader { border: 1px dashed #d9d9d9; border-radius: 6px; cursor: pointer; position: relative; overflow: hidden; transition: border-color 0.3s; }
.logo-uploader:hover { border-color: #409eff; }
.logo-uploader-icon { font-size: 28px; color: #8c939d; width: 120px; height: 120px; line-height: 120px; text-align: center; display: block; }
.logo { width: 120px; height: 120px; display: block; object-fit: cover; }
.backup-section { margin-top: 20px; }
.backup-card { margin-bottom: 20px; }
.backup-content { text-align: center; padding: 20px; }
.backup-description { color: #606266; margin-bottom: 20px; line-height: 1.6; }
.backup-actions { display: flex; gap: 16px; justify-content: center; }
@media (max-width: 768px) {
  .settings-form { max-width: 100%; }
  .backup-actions { flex-direction: column; align-items: center; }
  .logo-uploader-icon, .logo { width: 80px; height: 80px; line-height: 80px; }
}
</style>
